<template>
  <a-row class="box" :gutter="16" >
    <a-col class="right-line" :span="6" >
      <role-list @select="handleRoleSelected"></role-list>
    </a-col>
    <a-col :span="18" >
      <!-- 保存按钮-固钉 -->
      <div>
        <a-button class="save-btn" type="primary" @click="saveAssigment">保存</a-button>
        <a-row>
          <a-col :span="20" :offset="2">
            <a-card v-for="(pages,tag) in map" :key="tag" :bordered="false" >
              <!-- 模块 -->
              <a-divider>
                <a class="module-title" >{{tag}}</a>
              </a-divider>
              <!-- 菜单 -->
              <div class="page" v-for="page in pages" :key="page.code">
                <a-row class="menu">
                  <!-- 左：菜单名 -->
                  <a-col :span="22">
                    <a class="title" >{{page.name}}</a>
                  </a-col>
                  <!-- 右：switch按钮 -->
                  <a-col :span="2">
                    <a-switch class="button"
                              :checked="page.checked"
                              @change="(checked)=>{onPageCheckedChange(checked,page)}" />
                  </a-col>
                </a-row>
                <!-- 分割线-虚线 -->
                <a-divider class="dash-line" dashed />
                <a-row class="buttons">
                  <!-- 左： 页面的按钮 -->
                  <a-col :span="20">
                    <a-checkbox-group class="left"
                                      v-model="page.checkedButtonCodes"
                                      :disabled="!page.checked"
                                      @change="(checkedCodes)=>{onCheckedButtonsChange(checkedCodes,page)}">
                      <a-row>
                        <a-col class="chk-box-col" :span="6" v-for="button in page.children" :key="button.code" >
                          <a-checkbox :value="button.code">{{button.name}}</a-checkbox>
                        </a-col>
                      </a-row>
                    </a-checkbox-group>
                  </a-col>
                  <!-- 右： 全选 -->
                  <a-col :span="4">
                    <a-checkbox class="right"
                                :disabled="!page.checked"
                                :indeterminate="page.indeterminate"
                                @change="(e)=>{onCheckAllChange(e,page)}"
                                :checked="page.checkAllButtons">
                      全选</a-checkbox>
                  </a-col>
                </a-row>

              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

    </a-col>
  </a-row>
</template>

<script>

  import {findPages} from "@/api/view"
  import {findRoles,assignPageAndButtonPermissions,findRoleAssignedPageAndButtonPermissions} from "@/api/role"
  import RoleList from "../RoleList"
  import {groupBy} from 'lodash'
  import {mixin, mixinDevice} from '@/utils/mixin'
  import FooterToolBar from '@/components/FooterToolbar'

  export default {

    mixins: [mixin, mixinDevice],

    name: 'RoleAssignViewPermission',

    data(){
      return {
        loading: false,
        /**
         * map: [
         *   {
         *     '系统管理': {
         *        checked : true // switch按钮状态
                  indeterminate : false // 全选checkbox状态
                  checkAllButtons : false // 是否全选所有按钮
                  checkedButtonCodes : [] // 记录当前选中的按钮
                  children: [] // 按钮（操作）权限
         *     }
         *   }
         * ]
         */
        map: [],
        roleId: null
      }
    },

    components: {
      RoleList,
      FooterToolBar
    },

    created() {
      this.queryData()
    },

    methods: {
      queryData(){
        findPages().then(resp=>{
          let map = groupBy(resp.result.list,'tag')
          Object.values(map).forEach(pages=>{
            pages.forEach(page=>{
              page.checked = true // switch按钮状态
              page.indeterminate = false // 全选checkbox状态
              page.checkAllButtons = false // 是否全选所有按钮
              page.checkedButtonCodes = [] // 记录当前选中的按钮
            })
          })
          this.map = map
        })
      },
      handleRoleSelected(roleId){
        this.roleId = roleId
        if (!this.roleId){
          return false
        }
        findRoleAssignedPageAndButtonPermissions(this.roleId).then(resp=>{
          const roleAccessibleViewCodes = new Set(resp.result.list)
          Object.values(this.map).flat().forEach(page=>{
            const checkAllButton = roleAccessibleViewCodes.has(`${page.code}.*`)
            const checkedButtonCodes = page.children.filter(b=>roleAccessibleViewCodes.has(b.code)).map(b2=>b2.code)
            // switch按钮状态
            page.checked = roleAccessibleViewCodes.has(page.code)
            // 全选checkbox状态
            page.indeterminate = !checkAllButton && checkedButtonCodes.length < page.children.length
            if (checkedButtonCodes.length===0){
              page.indeterminate = null
            }
            // 是否全选所有按钮
            page.checkAllButtons = checkAllButton
            // 记录当前选中的按钮
            page.checkedButtonCodes = checkAllButton ? page.children.map(b=>b.code) : checkedButtonCodes
          })
        })
      },

      onPageCheckedChange(checked,page){
        page.checked = checked
        console.log('page checked change, checked: %o, page.checked: %o',checked,page.checked)
      },

      onCheckedButtonsChange(checkedList,page){
        page.indeterminate = !!checkedList.length && checkedList.length < page.children.length;
        page.checkAllButtons = checkedList.length === page.children.length;
      },

      onCheckAllChange(e,page) {
        let checkAllButtons = e.target.checked;
        page.indeterminate = false
        page.checkAllButtons = checkAllButtons
        page.checkedButtonCodes = checkAllButtons ? page.children.map(b=>b.code) : []
      },

      saveAssigment(){
        if (!this.roleId){
          this.$message.warn('必须选择一个角色以分配功能权限')
          return false
        }
        let accessibleViews = []
        Object.values(this.map).flat().forEach(page=>{
          if (page.checked){
            // type: 1 --> 菜单、页面
            accessibleViews.push(this.createAccessibleView(1,page.code))
            if (page.checkAllButtons){
              // type: 2 --> 按钮，  code: UserManage.* --> 拥有UserManage功能下所有操作权限
              accessibleViews.push(this.createAccessibleView(2,`${page.code}.*`))
            }else{
              page.checkedButtonCodes.forEach(bcode=>{
                // type: 2 --> 按钮，  code: UserManage.Edit --> 具体某个操作权限
                accessibleViews.push(this.createAccessibleView(2,bcode))
              })
            }
          }
        })
        assignPageAndButtonPermissions(this.roleId,accessibleViews).then(resp=>{
          this.$message.success('保存功能权限成功')
        })
      },

      createAccessibleView(type,viewCode){
        return {
          roleId: this.roleId,
          viewCode: viewCode,
          type: type
        }
      }


    }

  }
</script>

<style lang="less" scoped>
  .box{
    height: 100%;
    & .right-line{
      height: 100%; border-right: 1px solid #e8e8e8;
    }
    & .save-btn{
      position: fixed;
      right: 90px;
      z-index: 3;
    }
    & .module-title{
      font-size: 22px; color: #303133;
    }
    & .page{
      margin-bottom: 12px;
      & .menu{
        & .title{
          font-size: 18px;
        }
        & .button{
          float: right;
        }
      }
      & .dash-line{
        margin-top: 10px; margin-bottom: 10px;
      }
      & .buttons{
        margin-bottom: 24px;
        & .left{
          width: 100%;
          & .chk-box-col{
            margin-bottom: 10px;
          }
        }
        & .right{
          float:right;
        }
      }
    }


  }

</style>
